/**
 * 根据省、市、区（县）匹配邮政编码
 * 概述：首先根据区（县）匹配，如果找到邮政编码，再根据匹配出的邮政编码与市级邮政编码做核对，
 * 如果前两位一致,则核对通过.不一致以市级邮政编码为准.再将邮政编码与省级核对,一致则通过,不一致以省级为准.
 * @Param province, city, district
 */
import consts from "@/config/const.js";
import { getCacheValue } from "@/methods/cache.js";
export const findPostCode = (province, city, district) => {
  var _postcode = null;
  var _districtCode = null;
  var _cityCode = null;
  var _provinceCode = null;
  // 区（县）
  if (district) {
    _districtCode = searchPostCodeByKey(district);
  }
  // 市
  if (city) {
    _cityCode = searchPostCodeByKey(city);
  }
  // 省
  if (province) {
    _provinceCode = searchPostCodeByKey(province);
  }
  // console.log(_provinceCode, _cityCode, _districtCode);
  // 如果有区（县）邮政编码
  if (_districtCode) {
    // 与市级做核对
    if (_cityCode) {
      if (checkPostCodePrefix(_districtCode, _cityCode)) {
        //核对通过, 继续与省级核对
        if (_provinceCode) {
          // 通过, 则使用区(县)邮政编码
          if (checkPostCodePrefix(_provinceCode, _cityCode)) {
            _postcode = _districtCode;
          } else {
            // 不通过,使用省级邮政编码
            _postcode = _provinceCode;
          }
        }
      } else {
        //区(县)与市级核对不通过, 使用市级邮政编码与省级邮政编码核对
        if (_provinceCode) {
          if (checkPostCodePrefix(_provinceCode, _cityCode)) {
            _postcode = _cityCode;
          } else {
            _postcode = _provinceCode;
          }
        } else {
          _postcode = _cityCode;
        }
      }
    } else if (_provinceCode) {
      if (checkPostCodePrefix(_provinceCode, _districtCode)) {
        _postcode = _districtCode;
      }
    }
  } else if (_cityCode) {
    if (_provinceCode) {
      _postcode = _cityCode;
      if (checkPostCodePrefix(_provinceCode, _cityCode)) {
        _postcode = _cityCode;
      } else {
        _postcode = _provinceCode;
      }
    }
  } else {
    _postcode = _provinceCode;
  }

  return _postcode || "";
};

function searchPostCodeByKey(key) {
  var pcode = null;
  const postCode = getCacheValue("json", "postCodes");
  if (consts.empty(postCode)) return pcode;
  if (key) {
    pcode = postCode[key];
  }
  if (!pcode && key.length > 1) {
    pcode = postCode[key.substring(0, key.length - 1)];
  }
  return pcode;
}

function checkPostCodePrefix(code1, code2) {
  if (code1.substring(0, 1) == code2.substring(0, 1)) {
    return true;
  }
  var num = Number(code1) - Number(code2);
  if (1 == Math.abs(num)) {
    return true;
  }
  return false;
}
